<?php
namespace classlib\core\view;
use classlib\core\lang;
use classlib\core\config;
class extjs extends view_abstract {
	/**
	 * 存放赋值的信息
	 * @var array
	 */
	private $smart;
	
	/**
	 * 存放存储的文件资料信息
	 * @var string
	 */
	private $file;
	
	/**
	 * 模板所在目录结构
	 * @var unknown $view
	 */
	private $view;
	
	/**
	 * 单页应用的模板
	 * @var unknown
	 */
	private $single;
	
	/**
	 * 构造函数，导出extjs对象
	 * Enter description here ...
	 * @param unknown_type $params
	 */
	public function __construct($params=null) {
		$config      = config::load('extjs', false);
		foreach($config as $key=>&$value) {
    		$this->$key = $value;
    	}
    	$this->smart = array('code'=>0);
    	$this->file  = '';
	}

	/**
	 * 变量赋值
	 * @param string $key
	 * @param mix    $val
	 * @return view_abstract
	 */
	public function assign($key, $val) {
		$this->smart[$key] = $val;
		return $this;
	}
	
	/**
	 * 变量赋值引用赋值
	 * @param string $key
	 * @param mix $val
	 * @return view_abstract
	 */
	public function assign_by_ref($key, &$val) {
		$this->smart[$key] = &$val;
		return $this;
	}

	/**
	 * 已经分配的变量的获取 默认取所有
	 * @param string $key
	 * @return mix
	 */
	public function get_template_vars($key=false) {
		if($key) {
			$data = isset($this->smart[$key])? $this->smart[$key]:false;
			return $data;
		}
		return $this->smart;
	}
	
	/**
	 * 错误码复制直接退出
	 * @param string $code
	 * @param string $msg
	 */
	public function assign_error($code, $msg) {
		$var   = array('msg'=>$msg);
		$this->display('404.ext.js');
		exit;
	}
	
	/**
	 * 将要输出的资料获取
	 * @param string  $tpl
	 * @param boolean $iscache
	 * @param string $lang
	 * @return string
	 */
	public function fetch($tpl=false, $lang='extjs') {
		$file      = $this->view.$tpl;
		$var       = $this->get_template_vars();
		//加载Extjs语言包配置项
		$lcnf      = lang::inst($lang)->get(basename($file));
		$var['_L'] = empty($lcnf)? array():$lcnf;
	 	if (!file_exists($file)) {
	 		$file = $this->view.'404.ext.js';
	 	}
	 	unset($var['SCRIPT_NAME']);
	 	$data     = file_get_contents($file);
 		$var      = json_encode($var);
		$data     = str_replace('<?#$respons?>', $var, $data);
	 	return $data;
	}

	/**
	 * 重载Smarty输出的资料输出
	 * @param string  $tpl
	 * @param string  $cacheid  区别同一个页面不同展示模版
	 * @param int     $lifetime
	 * @see Smarty  $caching
	 */
	public function display($tpl=false, $cacheid=null, $lifetime = -1) {
		$isextjs = (!isset($_REQUEST['re']) || strcmp($_REQUEST['re'], 'extjs') !== 0)? false:true;
		if (!$isextjs) {
			$view  = \classlib\core\view::inst('html');
			\src\logic\Cadmin::share_index($view);
			parent::display();
			$extjsobj= $this->fetch($tpl);
			$view->assign_by_ref('extjsobj', $extjsobj);
			$view->display($this->single);	
		} else {
			parent::display();
			echo $this->fetch($tpl);
		}
	}
}